package cn.leaves.wb.viewer;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.leaves.wb.db.bean.Profile;
import cn.leaves.wb.db.bean.User;
import cn.leaves.wb.db.dao.ProfileDAO;
import cn.leaves.wb.db.dao.UserDAO;

@Controller
public class ProfileViewer {
	private Log log = LogFactory.getLog(getClass());
	private ProfileDAO profileDAO;
	private UserDAO userDAO;

	@RequestMapping("/login")
	public String login() {
		return "login";
	}

	@RequestMapping("/register")
	public String register() {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public String register(Profile profile, User user, ModelMap model) {
		try {
			Date registerDate = new Date();
			profile.setCreated(registerDate);
			profileDAO.save(profile);
			profile = profileDAO.findByNickName(profile.getNickname());
			user.setId(profile.getId());
			user.setCreated(registerDate);
			userDAO.save(user);
		} catch (Exception e) {
			e.printStackTrace();
			return "exception";
		}
		return "success";
	}

	/**
	 * @param profileDAO
	 *            the profileDAO to set
	 */
	@Autowired
	public void setProfileDAO(ProfileDAO profileDAO) {
		this.profileDAO = profileDAO;
	}

	/**
	 * @param userDAO
	 *            the userDAO to set
	 */
	@Autowired
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

}
